<template>
  <div>
    <van-search
      v-model="keyword"
      show-action
      label="商品"
      background="#f66"
      placeholder="请输入搜索关键词"
      @search="onSearch"
    >
      <template #action>
        <div @click="onSearch">搜索</div>
      </template>
    </van-search>
    <h4>历史记录</h4>
    <div class="histories">
      <div v-for="his in histories"
        @click="search(his)"
        :key="his" class="his">
        {{ his }}
      </div>
    </div>
  </div>
</template>

<script>
/*
searchHis
*/
export default {
  data () {
    return {
      keyword: '',
      histories: localStorage.getItem('searchHis')
        ? JSON.parse(localStorage.getItem('searchHis'))
        : []
    }
  },
  methods: {
    search (his) {
      this.$router.replace({
        path: '/searchResult',
        query: {
          word: his
        }
      })
    },
    onSearch () {
      if (this.keyword.trim() === '') {
        return
      }
      // 存储历史记录
      let histories = localStorage.getItem('searchHis')
        ? JSON.parse(localStorage.getItem('searchHis'))
        : []
      histories.unshift(this.keyword)
      histories = [...new Set(histories)]
      // 限制一下 长度
      if (histories.length > 5) {
        histories.pop()
      }
      localStorage.setItem('searchHis', JSON.stringify(histories))
      this.$router.replace({
        path: '/searchResult',
        query: {
          word: this.keyword
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.histories{
  display: flex;
  flex-wrap:wrap;
  .his {
    padding: 8px 15px;
    border-radius: 6px;
    background-color: #dc5;
    margin-right: 5px;
    margin-top: 10px;
  }
}
</style>
